package cn.edu.ctbu.sbadmin.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
public class FileUtil {

	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}


	/**
	 * 保存文件到固定的目录
	 *
	 * @param file
	 * @return
	 */
	public static String saveFile(MultipartFile file, String path) {
		UUID uuid = UUID.randomUUID();//生成唯一标识
		String originalFilename = file.getOriginalFilename();//取得原文件名
		String extendName = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());//继承源文件名中的后缀部分
		String fileName = uuid.toString() + extendName;//命新名称为标识+后缀
		Date date = new Date();
		String secpath=path +"/"+new SimpleDateFormat("yyyy/MM/dd/").format(date);//路径中加入时间戳即分日期保存

		try {
			String staticPath = ResourceUtils.getURL("classpath:static").getPath()
					.replace("%20", " ");
			File newFileName = new File(staticPath + "/" + secpath + "/" + fileName);
//判断文件夹是否存在，不存在则新建
			if (!newFileName.getParentFile().exists())
				newFileName.getParentFile().mkdirs();
			file.transferTo(newFileName);
		} catch (Exception e) {
			log.info(e.getMessage());
		}
		return "/"+secpath + "/" + fileName;//返回保存路径
	}

	public static String saveFile(MultipartFile file) {
		return saveFile(file, "upload");
	}

}
